import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../common/mixins/user_profile_mixin.dart';

class MessageChatController extends GetxController with UserProfileMixin {
  MessageChatController();

  // 聊天对象信息
  late String userName;
  late String userAvatar;
  late String userId;

  // 消息列表
  RxList<ChatMessage> messageList = <ChatMessage>[].obs;

  // 文本输入控制器
  final TextEditingController textController = TextEditingController();

  // 滚动控制器
  final ScrollController scrollController = ScrollController();

  _initData() {
    // 从路由参数获取用户信息
    final args = Get.arguments as Map<String, dynamic>?;
    userName = args?['name'] ?? '未知用户';
    userAvatar = args?['avatar'] ?? '';
    userId = args?['userId'] ?? '';

    // 初始化消息数据
    _loadChatMessages();

    update(["message_chat"]);
  }

  // 加载聊天消息
  void _loadChatMessages() {
    // 模拟历史消息
    messageList.value = [
      ChatMessage(
        id: '1',
        content: '你好，在吗？',
        isSelf: false,
        time: DateTime.now().subtract(const Duration(minutes: 10)),
      ),
      ChatMessage(
        id: '2',
        content: '在的，有什么事吗？',
        isSelf: true,
        time: DateTime.now().subtract(const Duration(minutes: 9)),
      ),
      ChatMessage(
        id: '3',
        content: '想问一下关于任务的事情',
        isSelf: false,
        time: DateTime.now().subtract(const Duration(minutes: 5)),
      ),
    ];
  }

  // 发送消息
  void sendMessage() {
    final text = textController.text.trim();
    if (text.isEmpty) return;

    final message = ChatMessage(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      content: text,
      isSelf: true,
      time: DateTime.now(),
    );

    messageList.add(message);
    textController.clear();

    // 滚动到底部
    Future.delayed(const Duration(milliseconds: 100), () {
      if (scrollController.hasClients) {
        scrollController.animateTo(
          scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  @override
  void onClose() {
    textController.dispose();
    scrollController.dispose();
    super.onClose();
  }
}

// 聊天消息模型
class ChatMessage {
  final String id;
  final String content;
  final bool isSelf;
  final DateTime time;

  ChatMessage({
    required this.id,
    required this.content,
    required this.isSelf,
    required this.time,
  });
}

